package org.yxing.demo.test;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

public class ActionBarHelper {
    
    protected ActionBarActivity mActivity;
    
    public ActionBarHelper createInstance(ActionBarActivity activity) {
        return new ActionBarHelper(activity);
    }
    
    public ActionBarHelper(ActionBarActivity activity) {
        mActivity = activity;
    }
    
    public void onCreate(Bundle savedInstanceState) {
        mActivity.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    }
    
    public void onPostCreate(Bundle savedInstanceState) {
        mActivity.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
                R.layout.actionbar_compat);
        
        setupActionBar();
        
        ActionBar actionBar = new ActionBar();
        mActivity.onCreateActionbar(actionBar);
        
        for (int i = 0; i < actionBar.size(); i ++) {
            addActionItem(actionBar.getItem(i));
        }

    }
    
    public void setupActionBar() {
        final ViewGroup actionBarCompat = getActionBarCompat();
        
        //Add title text
        TextView titleText = new TextView(mActivity, null, R.attr.actionBarCompatTitleStyle);
        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
        params.weight = 1;
        titleText.setLayoutParams(params);
        titleText.setText(mActivity.getTitle());
        actionBarCompat.addView(titleText);
    }
    
    private void addActionItem(final ActionBarItem item) {
        final ViewGroup actionBarCompat = getActionBarCompat();
        ImageButton actionButton = new ImageButton(mActivity, null, R.attr.actionbarCompatItemStyle);
        actionButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT));
        actionButton.setImageResource(item.getIconRes());
        actionButton.setScaleType(ImageView.ScaleType.CENTER);
        actionButton.setOnClickListener(new OnClickListener() {
            
            public void onClick(View v) {
                mActivity.onActionBarItemSelected(item);
            }
        });
        actionBarCompat.addView(actionButton);
    }
    
    protected void onTitleChanged(CharSequence title, int color) {
        TextView titleView = (TextView) mActivity.findViewById(R.id.actionbar_compat_title);
        if (titleView != null) {
            titleView.setText(title);
            titleView.setTextColor(color);
        }
    }
    
    private ViewGroup getActionBarCompat() {
        return (ViewGroup) mActivity.findViewById(R.id.actionbar_compat);
    }
}
